package com.scs.application.core.pdf.service;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.itextpdf.barcodes.Barcode128;
import com.itextpdf.barcodes.BarcodeQRCode;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.layout.property.VerticalAlignment;
import com.itextpdf.styledxmlparser.jsoup.helper.StringUtil;
import com.scs.application.core.pdf.consts.PdfExportConsts;
import com.scs.application.core.pdf.entity.PdfExportFormItem;
import com.scs.application.core.pdf.entity.PdfExportGridColumn;
import com.scs.application.core.pdf.entity.PdfExportParams;
import com.scs.application.core.pdf.enums.PdfPageDirection;
import com.scs.application.core.pdf.enums.SpacingMode;
import com.scs.application.core.pdf.enums.TextShowType;
import com.scs.application.core.pdf.exception.PdfExportException;
import com.scs.application.core.pdf.handler.HeaderHandler;
import com.scs.application.core.pdf.handler.WatermarkingEventHandler;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.itextpdf.layout.property.AreaBreakType.NEXT_PAGE;

/**
 * @description:
 */

@Data
public class PdfExportService extends ExportCommonService {
    private static final Paragraph BLANK_ROW = new Paragraph("\n");
    private static final Logger log = LoggerFactory.getLogger(PdfExportService.class);

    static {
        PdfFontFactory.registerSystemDirectories();
    }

    private OutputStream outputStream;

    private List<PdfExportParams> exportParamsList;

    private PdfFont pdfFont;

    private static final int DEFAULT_FONT_SIZE = 12;

    private static final String DEFAULT_FONT_PROGRAM = "STSong-Light";

    public PdfExportService(OutputStream outputStream, PdfExportParams exportParams) {
        this.outputStream = outputStream;
        this.exportParamsList = Lists.newArrayListWithCapacity(1);
        exportParamsList.add(exportParams);
    }

    public PdfExportService(OutputStream outputStream, List<PdfExportParams> exportParamsList) {
        this.outputStream = outputStream;
        this.exportParamsList = exportParamsList;
    }


    public void export() {
        try {
            _export();
        } catch (Exception e) {
            throw new PdfExportException("PDF导出失败", e);
        }
    }

    private void _export() throws Exception {

        if(exportParamsList == null || exportParamsList.isEmpty()) {
            return;
        }
        this.pdfFont = createFont();
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outputStream));
        Document doc = new Document(pdfDoc);
        doc.setFont(pdfFont);
        int totalPage = 0;
        PageSize pageSize = PageSize.Default;

        for(int i = 0; i < exportParamsList.size(); i++) {
            PdfExportParams exportParams = exportParamsList.get(i);
            int perRowsOfGrid = exportParams.getPerRowsOfGrid();

            pageSize = exportParams.getPageSize();

            List rawData = exportParams.getGridData();
            rawData = rawData == null ? new ArrayList() : rawData;
            int size = rawData.size();
            int selfPage = (int) Math.ceil(size * 1.0 / perRowsOfGrid);
            totalPage += selfPage;

            if (i == 0) {
                String watermark = exportParams.getWatermark();
                if (!StringUtil.isBlank(watermark)) {
                    pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE,
                            new WatermarkingEventHandler(pdfFont, watermark, exportParams.getWatermarkFontSize(), exportParams.getBackgroundImageBytes()));
                }

                // 方向
                PageSize tmpPageSize = pageSize;
                if (exportParams.getPageDirection() == PdfPageDirection.TRANSVERSE) {
                    tmpPageSize = pageSize.rotate();
                }
                pdfDoc.setDefaultPageSize(tmpPageSize);
            } else {
                doc.add(new AreaBreak(NEXT_PAGE));
            }

            SpacingMode spacingMode = exportParams.getSpacingMode();

            for (int ii = 0; ii < selfPage; ii++) {
                if (ii != 0) {
                    doc.add(new AreaBreak(NEXT_PAGE));
                }
                if (exportParams.getFlagTopTitle()) {
                    addTopTitle(doc, exportParams);
                } else {
                    addTitle(doc, exportParams);
                    if (spacingMode == SpacingMode.NORMAL) {
                       //doc.add(BLANK_ROW);
                    }
                }

                addHeader(doc, exportParams);
                if (spacingMode == SpacingMode.NORMAL) {
                    //doc.add(BLANK_ROW);
                }

                int beginIndex = ii * perRowsOfGrid;
                int endIndex = Math.min(size, (ii + 1) * perRowsOfGrid);
                List<?> data = rawData.subList(beginIndex, endIndex);
                addGrid(doc, data, exportParams, beginIndex);
                if(data.size() != rawData.size() || (exportParams.getSubFooters() != null && exportParams.getSubFooters().size() > 0 )) {
                    addSubFooter(doc, data, exportParams.getGridColumns(), exportParams.getSubFooters());
                }
                if (spacingMode == SpacingMode.NORMAL) {
                    //doc.add(BLANK_ROW);
                }
                if (ii == selfPage - 1 || exportParams.getFlagShowFootEveryPage()) {
                    addFooter(doc, exportParams);
                }
                PdfFormXObject template = new PdfFormXObject(new Rectangle(pageSize.getHeight() - 50, pageSize.getWidth() - 20, 30, 30));
                pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new HeaderHandler(template, pdfFont, totalPage, exportParams.getStrHeaderDate()));
            }
        }

        doc.close();
    }

    protected PdfFont createFont() throws IOException {
        return PdfFontFactory.createRegisteredFont("simsun", PdfEncodings.IDENTITY_H,true);
        // return PdfFontFactory.createFont(DEFAULT_FONT_PROGRAM, "UniGB-UCS2-H", true);
    }

    private void addBackgroundImage(Document doc, PdfPage pdfPage, PdfExportParams exportParams) throws Exception {

        byte[] backgroundImageBytes = exportParams.getBackgroundImageBytes();
        if (backgroundImageBytes == null || backgroundImageBytes.length == 0) {
            return;
        }

        ImageData imageData = ImageDataFactory.create(backgroundImageBytes);
        PdfCanvas canvas = new PdfCanvas(pdfPage);
        canvas.addImage(imageData, pdfPage.getPageSize(), false);

       /* int numberOfPages = doc.getPdfDocument().getNumberOfPages();
        for (int i = 0; i < numberOfPages; i++) {
            PdfPage page = doc.getPdfDocument().getPage(i + 1);
            PdfCanvas canvas = new PdfCanvas(page);
            canvas.addImage(imageData, page.getPageSize(), false);
        }*/
    }

    private void addGrid(Document doc, List data, PdfExportParams exportParams, int rowIndex) throws Exception {

        /*PdfExportGrid grid = exportParams.getGrid();
        if (grid == null) {
            return;
        }*/
        List<PdfExportGridColumn> columns = exportParams.getGridColumns();
        if (columns == null) {
            return;
        }
        int gridSpan = exportParams.getGridSpan();

        Table gridTable = new Table(UnitValue.createPercentArray(gridSpan)).useAllAvailableWidth();
        gridTable.setBorder(Border.NO_BORDER);
        gridTable.setKeepTogether(true);
        for (PdfExportGridColumn column : columns) {
            Cell cell = new Cell(1, column.getSpan());
            cell.add(new Paragraph(String.format("%s", column.getLabel())).setFontSize(columns.get(0).getFontSize()))
                    .setTextAlignment(TextAlignment.CENTER).setBold();
            gridTable.addHeaderCell(cell);
        }

        for (Object datum : data) {
            for (PdfExportGridColumn column : columns) {
                String fieldName = column.getField();
                Object value = null;
                if("udi".equals(fieldName)) {
                    log.info("111");
                }

                try {
                    if (fieldName.equalsIgnoreCase("rowIndex")) {
                        //如果是序号
//                        value = gridTable.getChildren().size() / columns.size() + 1;
                        value = rowIndex + gridTable.getNumberOfRows() + 1;
                    } else {
                        value = getFieldValue(datum, fieldName);
                    }
                } catch (NoSuchFieldException e) {
                    throw e;
                }

                String formatValue = formatValue(value, column.getField());

                Cell cell = new Cell(1, column.getSpan());

                PageSize defaultPageSize = doc.getPdfDocument().getDefaultPageSize();

                float columnWidth = defaultPageSize.getWidth() / gridSpan * column.getSpan();


                TextShowType textShowType = column.getTextShowType();
                int height = column.getHeight();

                TextAlignment textAlignment = column.getTextAlignment();

//                int dataFontSize = PdfExportConsts.GRID_DATA_FONT_SIZE;
                int dataFontSize = column.getFontSize();
                if (textShowType == TextShowType.PLAIN) {
                    // 每行显示字符个数
                    int numberOfRow = (int) Math.floor(columnWidth / (dataFontSize / 2));
                    if (StringUtils.isContainChinese(formatValue)) {
                        // 包含中文每行显示的字符个数较少
                        numberOfRow = (int) Math.floor(columnWidth / (dataFontSize + 3));
                    }

                    int rows = (int) Math.ceil(formatValue.length() * 1.0 / numberOfRow);
                    Paragraph paragraph = new Paragraph();
                    for (int i = 0; i < rows; i++) {
                        int beginIndex = i * numberOfRow;
                        int endIndex = Math.min((i + 1) * numberOfRow, formatValue.length());
                        /*cell.add(
                                new Paragraph(String.format("%s", formatValue.substring(beginIndex, endIndex)))
                                        .setFontSize(dataFontSize)
                        ).setTextAlignment(textAlignment != null ? textAlignment : TextAlignment.CENTER);*/

                    }

                    // 换行
                    if (column.isLineBreak() && column.getLineMax() > 0) {
                        String[] strArr = StrUtil.cut(formatValue,column.getLineMax());
                        for (String str : strArr) {
                            paragraph.add(new Text(str));
                        }
                    } else {
                        paragraph.add(new Text(formatValue));
                    }
                    paragraph.setFontSize(dataFontSize);
                    cell.add(paragraph).setTextAlignment(textAlignment != null ? textAlignment : TextAlignment.CENTER);
                } else if (textShowType == TextShowType.BARCODE) {
                    Barcode128 code128 = new Barcode128(doc.getPdfDocument());
                    code128.setFont(column.isShowBarcodeText() ? pdfFont : null);
                    code128.setCode(formatValue);

                    PdfFormXObject xObject = code128.createFormXObject(doc.getPdfDocument());
                    cell.add(new Image(xObject).setAutoScale(true).scale(0.7f, 0.7f));

                } else if (textShowType == TextShowType.QRCODE) {
                    BarcodeQRCode barcodeQRCode = new BarcodeQRCode(formatValue);

                    PdfFormXObject xObject = barcodeQRCode.createFormXObject(doc.getPdfDocument());
                    cell.add(new Image(xObject).setHeight(height).setAutoScale(true));
                }


                gridTable.addCell(cell);
            }
        }

//        long count = columns.stream().filter(o -> o.isSummary()).count();
//        if (count == 0) {
//            doc.add(gridTable);
//            return;
//        }

//        for (PdfExportGridColumn column : columns) {
//            Cell cell = new Cell(1, column.getSpan());
//            if (!column.isSummary() || !isEndPage) {
//                gridTable.addFooterCell(cell);
//                continue;
//            }
//            double sum = wholeList.stream().mapToDouble(o -> {
//                try {
//                    Object value = getFieldValue(o, column.getField());
//                    if (value == null || !StringUtils.isNumeric(value.toString())) {
//                        return 0.0;
//                    }
//                    return Double.parseDouble(value.toString());
//                } catch (Exception e) {
//                    return 0.0;
//                }
//            }).sum();
//            cell.add(new Paragraph(String.format("%.2f", sum))).setTextAlignment(TextAlignment.CENTER);
//            gridTable.addFooterCell(cell);
//        }

        doc.add(gridTable);
    }

    private Object getFieldValue(Object ins, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        try {
            Object value = null;
            if (ins instanceof Map) {
                value = ((Map) ins).get(fieldName);
            } else {
                Field field = ins.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                value = field.get(ins);
            }
            return value;
        } catch (NoSuchFieldException e) {
            throw e;
        } catch (IllegalAccessException e) {
            throw e;
        }
    }


    private void addFooter(Document doc, PdfExportParams exportParams) {
        _addHeaderOrFooter(doc, exportParams.getFooters());
    }

    private void addHeader(Document doc, PdfExportParams exportParams) {
        _addHeaderOrFooter(doc, exportParams.getHeaders());
    }

    //添加分页小计
    private void addSubFooter(Document doc, List data, List<PdfExportGridColumn> columns, List<PdfExportFormItem> subFooters) {
        if (data == null || data.isEmpty() || columns == null || columns.isEmpty()) {
            return;
        }

        Table table = new Table(UnitValue.createPercentArray(24)).useAllAvailableWidth();
        table.setBorder(Border.NO_BORDER);

        if(subFooters != null && subFooters.size() > 0) {
            for (PdfExportFormItem footer : subFooters) {
                Cell footLabelCell = new Cell(1, PdfExportConsts.GRID_DATA_SUB_SPAN_LEFT);
                footLabelCell.setBorderTop(Border.NO_BORDER);
                footLabelCell.add(new Paragraph(
                        new Text(footer.getLabel())).setFontSize(PdfExportConsts.SUBTITLE_FONT_SIZE).setTextAlignment(TextAlignment.RIGHT)
                );
                table.addCell(footLabelCell);

                Cell footValueCell = new Cell(1, PdfExportConsts.GRID_DATA_SUB_SPAN_RIGHT);
                footValueCell.setBorderTop(Border.NO_BORDER);
                footValueCell.add(new Paragraph(
                        new Text(footer.getValue().toString())).setFontSize(PdfExportConsts.SUBTITLE_FONT_SIZE).setTextAlignment(TextAlignment.LEFT)
                );
                table.addCell(footValueCell);
            }
        }

        List<PdfExportGridColumn> summaryList = columns.stream().filter(column -> column.isSummary()).collect(Collectors.toList());

        if (summaryList == null || summaryList.isEmpty()) {
            return;
        }

        // 获取标签最大长度
        int maxLength = summaryList.stream().mapToInt(o -> ("本页合计" + o.getLabel()).length()).max().getAsInt();

        for (PdfExportGridColumn column : summaryList) {
            Cell footLabelCell = new Cell(1, PdfExportConsts.GRID_DATA_SUB_SPAN_LEFT);
            footLabelCell.setBorderTop(Border.NO_BORDER);
            //cell.setBorder(Border.NO_BORDER);
            String label = "本页合计" + column.getLabel();
            double sum = data.stream().mapToDouble(o -> {
                try {
                    Object value = getFieldValue(o, column.getField());
                    if (value == null) {
                        return 0.0;
                    }
                    return Double.parseDouble(value.toString());
                } catch (Exception e) {
                    return 0.0;
                }
            }).sum();
            footLabelCell.add(new Paragraph(
                    new Text(StringUtils.repeat("\t", (maxLength - label.length())) + label)).setFontSize(PdfExportConsts.SUBTITLE_FONT_SIZE)
                    .setTextAlignment(TextAlignment.RIGHT)
            );
            table.addCell(footLabelCell);

            Cell footValueCell = new Cell(1, PdfExportConsts.GRID_DATA_SUB_SPAN_RIGHT);
            footValueCell.setBorderTop(Border.NO_BORDER);
            footValueCell.add(new Paragraph(
                    new Text(String.format("%s%.2f", "\t", sum))).setFontSize(PdfExportConsts.SUBTITLE_FONT_SIZE).setTextAlignment(TextAlignment.LEFT)
            );
            table.addCell(footValueCell);
        }
        doc.add(table);
    }

    private void _addHeaderOrFooter(Document doc, List<PdfExportFormItem> items) {

        if (items == null || items.isEmpty()) {
            return;
        }

        Table table = new Table(UnitValue.createPercentArray(24)).useAllAvailableWidth();
        table.setBorder(Border.NO_BORDER);

        // 获取标签最大长度
        int maxLength = items.stream().mapToInt(o -> o.getLabel().length()).max().getAsInt();

        for (PdfExportFormItem item : items) {
            int offset = item.getOffset();
            if (offset > 0) {
                Cell cell = new Cell(1, offset).setBorder(Border.NO_BORDER);
                table.addCell(cell);
            }

            Object value = item.getValue();

            Cell cell = new Cell(1, item.getSpan());
            if (!item.getHasBorder()) {
                cell.setBorder(Border.NO_BORDER);
            } else {
                cell.setBorderTop(Border.NO_BORDER);
            }
            String label = item.getLabel();
            String formatValue = formatValue(value, item.getField());
            TextShowType textShowType = item.getTextShowType();
            float height = item.getHeight();

            if (textShowType == TextShowType.PLAIN) {
                cell.add(new Paragraph(
                        new Text(StringUtils.repeat("\t", (maxLength - label.length())) + label).setBold()).setFontSize(PdfExportConsts.HEADER_FONT_SIZE)
                        .add(String.format("%s%s", "\t", formatValue)).setFontSize(PdfExportConsts.HEADER_FONT_SIZE)
                );
            } else if (textShowType == TextShowType.BARCODE) {

                Barcode128 code128 = new Barcode128(doc.getPdfDocument());
                code128.setFont(item.isShowBarcodeText() ? pdfFont : null);
                code128.setCode(formatValue);
                code128.setBarHeight(height);

                PdfFormXObject xObject = code128.createFormXObject(doc.getPdfDocument());
                cell.add(new Paragraph(new Text(label).setBold()).add("\t ")
                        .add(new Image(xObject).setHeight(height).setHorizontalAlignment(HorizontalAlignment.CENTER)));

            } else if (textShowType == TextShowType.QRCODE) {
                BarcodeQRCode barcodeQRCode = new BarcodeQRCode(formatValue);

                PdfFormXObject xObject = barcodeQRCode.createFormXObject(doc.getPdfDocument());
                cell.add(new Paragraph(new Text(label).setBold()).add("\t ")
                        .add(new Image(xObject).setHeight(height).setRelativePosition(0, height / 2, 0, 0)));
            }
            table.addCell(cell);
        }
        doc.add(table);

    }

    private String formatValue(Object value, String field) {
        if (value == null) {
            return "";
        }
        if (value instanceof Date) {
            return DateUtils.format((Date) value, "yyyy-MM-dd");
        }
        return value.toString();
    }

    private void addTopTitle(Document doc, PdfExportParams exportParams) { //置顶标题格式,条形码在左，二维码在右
        Table table = new Table(UnitValue.createPercentArray(24)).useAllAvailableWidth();

        int totalSpan = 24;
        int rowspan = 2;
        int titleSpan = totalSpan;

        String qrcodeText = exportParams.getQrcodeText();
        String barcodeText = exportParams.getBarcodeText();
        String subTitle = exportParams.getSubTitle();
        if (StringUtils.isNotBlank(qrcodeText) || StringUtils.isNotBlank(barcodeText)) {
            titleSpan -= 12;
        }

        if (StringUtils.isNotBlank(barcodeText)) {
            Cell barcodeCell = new Cell(rowspan, StringUtils.isNotBlank(barcodeText) ? 8 : 12);
            Barcode128 code128 = new Barcode128(doc.getPdfDocument());
            code128.setCode(barcodeText);
            code128.setBaseline(-1);

            PdfFormXObject xObject = code128.createFormXObject(doc.getPdfDocument());
            barcodeCell.add(new Image(xObject).setAutoScale(true));
            table.addHeaderCell(barcodeCell.setVerticalAlignment(VerticalAlignment.MIDDLE).setBorder(Border.NO_BORDER));

        }

        Cell titleCell = new Cell(1, titleSpan);
        titleCell.setBorder(Border.NO_BORDER);
        titleCell.add(new Paragraph(exportParams.getTitle())
                .setTextAlignment(TextAlignment.LEFT).setFontSize(PdfExportConsts.TITLE_FONT_SIZE));
        table.addHeaderCell(titleCell);


        if (StringUtils.isNotBlank(subTitle)) {
            Cell subTitleCell = new Cell(1, titleSpan);
            subTitleCell.setBorder(Border.NO_BORDER);
            subTitleCell.add(new Paragraph(StringUtils.repeat("\t", 3) +subTitle)
                    .setTextAlignment(TextAlignment.LEFT).setFontSize(PdfExportConsts.SUBTITLE_FONT_SIZE));
            table.addHeaderCell(subTitleCell);
        }

        if (StringUtils.isNotBlank(qrcodeText)) {
            Cell qrcodeCell = new Cell(rowspan, StringUtils.isNotBlank(barcodeText) ? 4 : 12);
            BarcodeQRCode barcodeQRCode = new BarcodeQRCode(qrcodeText);

            PdfFormXObject xObject = barcodeQRCode.createFormXObject(doc.getPdfDocument());
            qrcodeCell.add(new Image(xObject).scaleToFit(60, 60));
            table.addHeaderCell(qrcodeCell.setVerticalAlignment(VerticalAlignment.MIDDLE).setBorder(Border.NO_BORDER));
        }

        doc.add(table);
    }

    private void addTitle(Document doc, PdfExportParams exportParams) {

        String subTitle = exportParams.getSubTitle();

        Table table = new Table(UnitValue.createPercentArray(24)).useAllAvailableWidth();

        int totalSpan = 24;
        int titleSpan = totalSpan;
        int rowspan = 3;

        String project = exportParams.getProject();
        String qrcodeText = exportParams.getQrcodeText();
        String barcodeText = exportParams.getBarcodeText();
        if (StringUtils.isNotBlank(qrcodeText) || StringUtils.isNotBlank(barcodeText)) {
            titleSpan -= 12;
        }

        Cell projectCell = new Cell(1, titleSpan);
        projectCell.setBorder(Border.NO_BORDER);
        projectCell.add(new Paragraph(StringUtils.defaultString(project))
                .setTextAlignment(TextAlignment.LEFT).setFontSize(PdfExportConsts.PROJECT_FONT_SIZE).setUnderline()
        );
        table.addHeaderCell(projectCell);

        if (StringUtils.isNotBlank(qrcodeText)) {
            Cell qrcodeCell = new Cell(rowspan, StringUtils.isNotBlank(barcodeText) ? 4 : 12);
            BarcodeQRCode barcodeQRCode = new BarcodeQRCode(qrcodeText);

            PdfFormXObject xObject = barcodeQRCode.createFormXObject(doc.getPdfDocument());
            qrcodeCell.add(new Image(xObject).scaleToFit(40, 40));
            table.addHeaderCell(qrcodeCell.setVerticalAlignment(VerticalAlignment.MIDDLE).setBorder(Border.NO_BORDER));
        }

        if (StringUtils.isNotBlank(barcodeText)) {
            Cell barcodeCell = new Cell(rowspan, StringUtils.isNotBlank(barcodeText) ? 8 : 12);
            Barcode128 code128 = new Barcode128(doc.getPdfDocument());
            code128.setCode(barcodeText);
            code128.setBaseline(-1);
            code128.setBarHeight(40);

            PdfFormXObject xObject = code128.createFormXObject(doc.getPdfDocument());
            barcodeCell.add(new Image(xObject).setAutoScale(true));
            barcodeCell.setHeight(40);
            table.addHeaderCell(barcodeCell.setVerticalAlignment(VerticalAlignment.MIDDLE).setBorder(Border.NO_BORDER));
        }


        Cell titleCell = new Cell(1, titleSpan);
        titleCell.setBorder(Border.NO_BORDER);
        titleCell.add(new Paragraph(exportParams.getTitle())
                .setTextAlignment(TextAlignment.CENTER).setFontSize(PdfExportConsts.TITLE_FONT_SIZE).setBold());
        table.addHeaderCell(titleCell);


        if (StringUtils.isNotBlank(subTitle)) {
            Cell subTitleCell = new Cell(1, titleSpan);
            subTitleCell.setBorder(Border.NO_BORDER);
            subTitleCell.add(new Paragraph(subTitle)
                    .setTextAlignment(TextAlignment.CENTER).setFontSize(PdfExportConsts.SUBTITLE_FONT_SIZE));
            table.addHeaderCell(subTitleCell);
        }
        doc.add(table);
        /*doc.add(new Paragraph(exportParams.getTitle()).setTextAlignment(TextAlignment.CENTER).setFontSize(20).setBold());
        if (StringUtils.isNotBlank(exportParams.getSubTitle())) {
            doc.add(new Paragraph(exportParams.getSubTitle()).setTextAlignment(TextAlignment.CENTER).setFontSize(15).setBold());
        }*/
    }
}
